package com.right.health.app.net;

import android.os.AsyncTask;
import android.text.TextUtils;

import com.magics.http.model.HttpParams;
import com.right.health.app.bean.UploadResponse;
import com.right.health.app.utils.Base64Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/*
 * Created by hopeliao on 2019-11-30
 *
 */
public class UploadApi extends IBaseApi {

    public void uploadFile(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        new AsyncTask<String, String, String>() {

            @Override
            protected String doInBackground(String... strings) {
                try {
                    File file = new File(strings[0]);
                    if (!file.exists()) {
                        return "";
                    }
                    return Base64Utils.encodeBase64File(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "";
            }

            @Override
            protected void onPostExecute(String result) {
                if(TextUtils.isEmpty(result)) {
                    return;
                }

                HttpParams params = new HttpParams();

                try {
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.put(result);

                    JSONObject root = new JSONObject();
                    root.put("imgurls", jsonArray);

                    params.addFormParam("jsonstr", root.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                doPostJson(HttpConstants.UPLOAD_FILE, params, UploadResponse.class);
            }

        }.execute(filePath);
    }
}
